package com.jerry.chat.netty;

import com.google.gson.Gson;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.util.HashMap;

public class WSServerHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    private static ChannelGroup users = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    private static HashMap<String, Channel> userChannelRel = new HashMap<>();

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        var content = msg.text();
        System.out.println("服务器收到消息：" + content);
        var gson = new Gson();
        var dataContent = gson.fromJson(content, DataContent.class);
        if (dataContent.getAction() == EnumMsgAction.CONNECT.type) {
            users.add(ctx.channel());
            userChannelRel.put(dataContent.getChatMsg().getSenderId(), ctx.channel());
        } else if (dataContent.getAction() == EnumMsgAction.CHAT.type) {
            var receiverChannel = userChannelRel.get(dataContent.getChatMsg().getReceiverId());
            if (receiverChannel != null) {
                receiverChannel.writeAndFlush(new TextWebSocketFrame(content));
            } else {

            }
        } else if (dataContent.getAction() == EnumMsgAction.SIGNED.type) {

        } else if (dataContent.getAction() == EnumMsgAction.KEEPALIVE.type) {

        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channelActive");
    }

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        users.add(ctx.channel());
    }
}
